<script lang="ts" setup>
import {onBeforeMount, reactive, ref} from 'vue'
import {getAPI} from "@/api/MyAxiosAPI";
import type {
  ELOptions,
  PhaseInterface,
  ProjectInterface,
  ResponseInterface,
  TaskInterface,
  UserInterface
} from "@/type/models";
import {ElMessage} from "element-plus";
import router from "@/router";
import {Delete, DocumentAdd, Edit} from "@element-plus/icons-vue";
import Task from "@/components/Project/Task.vue"

const MOCK = false;
const API = getAPI(MOCK);

function goBack() {
  router.push("/project")
}

// --- project info ---
const projectInfo = reactive<ProjectInterface>({})
const userList = ref<Array<UserInterface>>([])

function gerProjectInfo() {
  let pId = localStorage.getItem("currentlyProjectId")
  API({
    url: "/project/info/" + pId,
    method: "get",
    headers: {
      Authorization: localStorage.getItem("token")
    }
  }).then(res => {
    let r: ResponseInterface = res.data
    if (r.code === 200) {
      Object.assign(projectInfo, r.data);
    }
  })
}

function getAllUserByProject() {
  let pId = localStorage.getItem("currentlyProjectId")
  API({
    url: "/project/user/" + pId,
    method: "GET",
    headers: {
      Authorization: localStorage.getItem("token")
    },
  }).then(res => {
    let r: ResponseInterface = res.data
    if (r.code === 200) {
      userList.value.splice(0, userList.value.length)
      userList.value.push(...r.data)
    }
  })
}

// --- project info end ---
// --- phase ---
const phaseList = reactive<Array<PhaseInterface>>([])

/**
 * 获取项目所有的phase
 */
function getAllPhase() {
  let pid = localStorage.getItem("currentlyProjectId")
  API({
    url: "/project/phase/view",
    method: "GET",
    headers: {
      Authorization: localStorage.getItem("token")
    },
    params: {
      pid: pid
    }
  }).then(res => {
    let r: ResponseInterface = res.data
    if (r.code === 200) {
      phaseList.splice(0, phaseList.length)
      phaseList.push(...r.data)
    }
  })
}

// 增加新阶段
let addPhaseDialog = ref(false)
let addPhaseName = ref("")

function addPhase() {
  addPhaseName.value = ""
  addPhaseDialog.value = true
}

function addPhaseAPI() {
  if (addPhaseName.value.length == 0) {
    ElMessage.warning("阶段名称不能为空")
    return
  }
  API({
    url: "/project/phase/create",
    method: "POST",
    headers: {
      Authorization: localStorage.getItem("token")
    },
    data: {
      name: addPhaseName.value,
      pId: localStorage.getItem("currentlyProjectId")
    }
  }).then(res => {
    let r: ResponseInterface = res.data
    if (r.code === 200) {
      ElMessage.success("创建成功")
      getAllPhase()
      addPhaseDialog.value = false
    }
  })
}

// 修改当前阶段
let editPhaseDialog = ref(false)
let oldPhaseName = ref("")
let editPhaseName = ref("")
let currentPhaseId = ref("")

function editPhase(phase: PhaseInterface) {
  oldPhaseName.value = phase.name
  editPhaseName.value = phase.name
  currentPhaseId.value = phase.phaseId
  editPhaseDialog.value = true
}

function updatePhaseAPI() {
  if (oldPhaseName.value === editPhaseName.value) {
    ElMessage.warning("阶段名称未修改")
    return
  }
  if (editPhaseName.value.length == 0) {
    ElMessage.warning("阶段名称不能为空")
    return
  }
  API({
    url: "/project/phase/update",
    method: "POST",
    headers: {
      Authorization: localStorage.getItem("token")
    },
    data: {
      name: editPhaseName.value,
      phaseId: currentPhaseId.value,
      pId: localStorage.getItem("currentlyProjectId")
    }
  }).then(res => {
    let r: ResponseInterface = res.data
    if (r.code === 200) {
      ElMessage.success("修改成功")
      getAllPhase()
      editPhaseDialog.value = false
    }
  })
}

// 删除阶段
function deletePhaseAPI(phase: PhaseInterface) {
  API({
    url: "/project/phase/delete",
    method: "DELETE",
    headers: {
      Authorization: localStorage.getItem("token")
    },
    data: {
      phaseId: phase.phaseId,
      pId: phase.pId
    }
  }).then(res => {
    let r: ResponseInterface = res.data
    if (r.code === 200) {
      ElMessage.success("删除成功")
      getAllPhase()
    }
  })
}

// --- phase end ---
// --- task ---
// 添加新任务
const addTaskForm = reactive<TaskInterface>({})
let addTaskDialog = ref(false)
// 待被选择的ELOptions
let userListELOptions = ref<ELOptions[]>([])
// 已经被选择的ELOptions
let selectedUserListELOptions = ref([])
// 当某个phase更新task后，值为phaseId，子组件监听值，如果与自己phaseId一样就触发刷新。
let reFlushPhaseId = ref<string>("")

function userListToELOptions() {
  // 将userList转为ELOptions
  let data: ELOptions[] = []
  for (let user of userList.value) {
    data.push({
      key: user.uid,
      label: user.nickname + "(" + user.email + ")",
      disabled: false
    })
  }
  return data;
}

function addTask(phase: PhaseInterface) {
  Object.assign(addTaskForm, {
    pId: phase.pId,
    phaseId: phase.phaseId,
    name: "",
    description: "",
    beginTime: "",
    endTime: ""
  })
  userListELOptions.value.splice(0, selectedUserListELOptions.value.length)
  userListELOptions.value = userListToELOptions()
  selectedUserListELOptions.value = []
  reFlushPhaseId.value = ""
  addTaskDialog.value = true
}

function addTaskAPI() {
  if (addTaskForm.name.length == 0) {
    ElMessage.warning("任务名称不能为空")
    return
  }
  //任务开始时间不能晚于结束时间
  if (addTaskForm.beginTime > addTaskForm.endTime) {
    ElMessage.warning("任务开始时间不能晚于结束时间")
    return
  }
  // 未分配人员警告
  let users = []
  if (selectedUserListELOptions.value.length == 0) {
    ElMessage.warning("未分配人员")
    return
  } else {
    for (let i of selectedUserListELOptions.value) {
      users.push({
        uid: i
      })
    }
  }
  API({
    url: "/project/phase/task/create",
    method: "POST",
    headers: {
      Authorization: localStorage.getItem("token")
    },
    data: {
      projectId: addTaskForm.pId,
      phaseId: addTaskForm.phaseId,
      name: addTaskForm.name,
      description: addTaskForm.description,
      beginTime: addTaskForm.beginTime,
      endTime: addTaskForm.endTime,
      users: users
    }
  }).then(res => {
    let r: ResponseInterface = res.data
    if (r.code === 200) {
      ElMessage.success("创建成功")
      reFlushPhaseId.value = addTaskForm.phaseId
      addTaskDialog.value = false
    }
  })
}

// --- task end ---
// --- 生命周期 ---
onBeforeMount(() => {
  gerProjectInfo()
  getAllUserByProject()
  getAllPhase();
})
// --- 生命周期 end ---
</script>

<template>
  <el-page-header @back="goBack">
    <template #content>
      <span class="text-large font-600 mr-3"> {{ projectInfo.name }} </span>
    </template>
  </el-page-header>
  <div>
    <el-button @click="addPhase">创建阶段</el-button>
  </div>
  <el-row>
    <el-col v-for="phase in phaseList" :key="phase.phaseId" :span="8">
      <el-card shadow="hover">
        <template #header>
          <div class="card-container">
            <span class="card-name">{{ phase.name }}</span>
            <el-button-group>
              <el-button :icon="DocumentAdd" type="primary" @click="addTask(phase)">新增任务</el-button>
              <el-button :icon="Edit" type="primary" @click="editPhase(phase)">修改</el-button>
              <el-popconfirm title="确定要删除此阶段吗？" @confirm="deletePhaseAPI(phase)">
                <template #reference>
                  <el-button :icon="Delete" type="primary">删除</el-button>
                </template>
              </el-popconfirm>
            </el-button-group>
          </div>
        </template>
        <div class="task-container">
          <Task :phaseId="phase.phaseId" :reFlushPhaseId="reFlushPhaseId"></Task>
        </div>
      </el-card>
    </el-col>
  </el-row>
  <div>
    <el-dialog
        v-model="addPhaseDialog"
        title="创建新阶段"
        width="500"
    >
      <el-input v-model="addPhaseName" placeholder="阶段名称"/>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addPhaseDialog = false">取消</el-button>
          <el-button type="primary" @click="addPhaseAPI">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
        v-model="editPhaseDialog"
        title="修改阶段名称"
        width="500"
    >
      <el-input v-model="editPhaseName" placeholder="阶段名称"/>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editPhaseDialog = false">取消</el-button>
          <el-button type="primary" @click="updatePhaseAPI">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
        v-model="addTaskDialog"
        title="创建新任务"
    >
      <el-form :model="addTaskForm" label-width="120px">
        <el-form-item label="任务名称">
          <el-input v-model="addTaskForm.name"/>
        </el-form-item>
        <el-form-item label="任务详情">
          <el-input v-model="addTaskForm.description" type="textarea"/>
        </el-form-item>
        <el-form-item label="任务开始时间">
          <el-date-picker
              v-model="addTaskForm.beginTime"
              placeholder="请选择任务开始时间"
              type="datetime"
          />
        </el-form-item>
        <el-form-item label="任务结束时间">
          <el-date-picker
              v-model="addTaskForm.endTime"
              placeholder="请选择任务结束时间"
              type="datetime"
          />
        </el-form-item>
        <el-form-item label="队员">
          <el-transfer
              v-model="selectedUserListELOptions"
              :data="userListELOptions" :titles="['备选人员', '选中人员']"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addTaskDialog = false">取消</el-button>
          <el-button type="primary" @click="addTaskAPI">
            创建
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>

.card-container {
  display: flex;
  justify-content: flex-start; /* 默认值，可以省略 */
}

.card-name {
  margin-right: auto; /* 让文本与按钮之间有足够的间距 */
}

.task-container {
  height: 350px;
}
</style>